package com.alex.controller.ChatGpt;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.alex.controller.System.entity.RoleEntity;
import com.alex.enumType.TypeEnum;
import com.alex.sevice.ChatGptService;
import com.alibaba.fastjson.JSONObject;
import common.beans.ResultBean;
import common.beans.User;
import common.util.UserUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/ai")
@RestController
@Tag(name = "GPT_孔柳茜")
public class ChatGptController {

    @Autowired
    private ChatGptService chatGptService;


    @Operation(summary = "清空聊天信息", description = "清空聊天信息")
    @GetMapping("/clean")
    public ResultBean<Object> clean() {
        Integer uid = UserUtil.getUserUnloginAccess().getUid();
        try {
            Db.use().update(
                    Entity.create().set("deleted", 1), //修改的数据
                    Entity.create("chat_record").set("user_id", uid)); //where条件
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return new ResultBean<>("操作成功");
    }

    @Operation(summary = "回显历史记录", description = "回显历史记录")
    @GetMapping("/history")
    public ResultBean<Object> history() {

        Integer uid = UserUtil.getUserUnloginAccess().getUid();
        List<Entity> entityList2 = new ArrayList<>();
        try {
            List<Entity> entityList = Db.use().query("SELECT * FROM chat_record WHERE user_id = " + uid + " AND deleted = 0  ORDER BY id ASC ;");
            try {
                for (Entity entity : entityList) {
                    String content = entity.getStr("content");
                    if (content.contains("__ZFL__")) {
                        content = content.split("__ZFL__")[1];
                    }
                    entity.set("content", content);
                    entityList2.add(entity);
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
            return new ResultBean<>(entityList2);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return new ResultBean<>();
    }

    @Operation(summary = "学术助手所有接口", description = "接口以stream流式返回,参考各大 AI 聊天界面效果,根据 type 来区分是聊天还是各个右侧图标的功能")
    @PostMapping(value = "/ai_post", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void ai_post(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        String content = jsonObject.getString("content");
        Integer type = jsonObject.getInteger("type");
        Integer startFlag = jsonObject.getInteger("startFlag");
        if (null == startFlag) {
            startFlag = 0;
        }
        // 需要指定response的ContentType为流式输出，且字符编码为UTF-8
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        // 禁用缓存
        response.setHeader("Cache-Control", "no-cache");

        User user = UserUtil.getUserUnloginAccess();
        try {
            Db.use().insert(Entity.create("chat_record")
                    .set("role", RoleEntity.User)
                    .set("user_id", user.getUid())
                    .set("user_name", user.getRealname())
                    .set("unit_id", user.getGid())
                    .set("unit_name", user.getUnitName())
                    .set("content", content)
                    .set("content_type", type)
                    .set("sys_create_time", LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
                    .set("sys_update_time", LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
                    .set("deleted", 0));

        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        try {
            chatGptService.ai_web_chat(response, user, true, null, type, startFlag);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }


}

